param(
    [string]$Nasm = "nasm",
    [string]$Linker = "ld.lld",
    [string]$ImageBase = "",
    [string]$TextAddr = "0x00520000"
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$root = Resolve-Path (Join-Path $PSScriptRoot "..")
$buildDir = Join-Path $root "build"
if (-not (Test-Path $buildDir)) {
    New-Item -ItemType Directory -Path $buildDir | Out-Null
}

$asm = Join-Path $root "examples\hello32.asm"
$obj = Join-Path $buildDir "hello32.o"
$elf = Join-Path $buildDir "hello32.elf"
$dest = Join-Path $root "cmd\kernel\assets\hello32.elf"

& $Nasm "-f" "elf32" "-o" $obj $asm
if ($LASTEXITCODE -ne 0) { throw "NASM failed for hello32" }

# Prefer GNU-flavor LLD on Windows to avoid COFF driver's image-base errors
$linkArgs = @("-m", "elf_i386", "-e", "_start", "-Ttext", $TextAddr, "-o", $elf, $obj)
if ($ImageBase -ne "") {
    # If ld.lld resolves to the COFF driver (lld-link), this helps satisfy its base-image requirement.
    # Note: for GNU ld.lld (ELF), this flag is ignored/unsupported.
    $linkArgs += @("--image-base", $ImageBase)
}
$linked = $false

try {
    & $Linker @linkArgs
    if ($LASTEXITCODE -eq 0) { $linked = $true }
} catch {}

if (-not $linked) {
    # Try TinyGo's bundled GNU ld.lld
    $tg = Get-Command tinygo -ErrorAction SilentlyContinue
    if ($null -ne $tg) {
        try {
            $tinRoot = & tinygo env TINYGOROOT
            $tinLd = Join-Path $tinRoot "libexec\bin\ld.lld.exe"
            if (Test-Path $tinLd) {
                Write-Host "Using TinyGo GNU ld.lld at $tinLd"
                & $tinLd @linkArgs
                if ($LASTEXITCODE -eq 0) { $linked = $true }
            }
        } catch {}
    }
}

if (-not $linked) {
    # Try common LLVM installation path
    $llvmLd = Join-Path $env:ProgramFiles "LLVM\bin\ld.lld.exe"
    if (Test-Path $llvmLd) {
        Write-Host "Using LLVM GNU ld.lld at $llvmLd"
        & $llvmLd @linkArgs
        if ($LASTEXITCODE -eq 0) { $linked = $true }
    }
}

if (-not $linked) {
    $lldCmd = Get-Command lld -ErrorAction SilentlyContinue
    if ($null -ne $lldCmd) {
        $args2 = @("-flavor", "gnu") + $linkArgs
        & $lldCmd.Source @args2
        if ($LASTEXITCODE -eq 0) { $linked = $true }
    }
}

if (-not $linked) { throw "Link step failed for hello32 (ensure GNU ld.lld)" }

Copy-Item -Force $elf $dest
Write-Host "Built and installed sample ELF at $dest"